#!/usr/bin/env python
import numpy as np
from astropy.table import Table
import sys

#fill_tab.py table_thresis.ini 16 
# ptc_result.tab full 0 16 max 2 100
f = open(sys.argv[1])
lines = f.readlines()
nchan = int(sys.argv[2])
datas = np.zeros((nchan+2,len(lines)))
fmt = []
for i in range(len(lines)):
    f = lines[i].split(' ')[0]
    tab = Table.read(f,format='ipac')
    l = int(lines[i].split(' ')[2])
    h = int(lines[i].split(' ')[3])
    data = tab[lines[i].split(' ')[1]][l:h]
    worst_flag = lines[i].split(' ')[4]
    if len(lines[i].split(' ')) == 7:
        #print(lines[i].split(' '))
        digit = lines[i].split(' ')[5]
        coeff = float(lines[i].split(' ')[6][:-1])
        data = data * coeff
    else:
        print(lines[i].split(' '))
        print(lines[i].split(' ')[5])
        digit = lines[i].split(' ')[5][:-1]
    if worst_flag == 'abs':
        data = abs(data)
        worst = np.max(data)
    if worst_flag == 'min':
        worst = np.min(data)
    if worst_flag == 'max':
        worst = np.max(data)
    mean = np.mean(data)
    data = np.append(data,mean)
    data = np.append(data,worst)
    if digit[-1] == 'e':
        datas[:,i] = data
        fmt.append('%.2e')
    else:
        digit = int(digit)
        datas[:,i] = np.round(data,digit)
        fmt.append('%.'+str(digit)+'f')
np.savetxt(sys.argv[3],datas,fmt)
